package com.imooc.service.impl;

import com.imooc.service.WebSocket;
import com.imooc.utils.KeyUtil;
import com.imooc.converter.OrderMaster2OrderDTOConverter;
import com.imooc.dataobject.OrderDetail;
import com.imooc.dataobject.OrderMaster;
import com.imooc.dataobject.ProductInfo;
import com.imooc.dto.CartDTO;
import com.imooc.dto.OrderDTO;
import com.imooc.enums.OrderStatusEnum;
import com.imooc.enums.PayStatusEnum;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.repository.OrderDetailRepository;
import com.imooc.repository.OrderMasterRepository;
import com.imooc.service.OrderService;
import com.imooc.service.ProductInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**DAO 负责数据库的操作--- 简单固定
 * 这个地方是负责业务的处理
 * CONTROLLER 负责前端的电视调度 - 简单固定
 * 好好想想业务的处理。
 * 注意什么应该前端传，什么后端处理
 */

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private OrderMasterRepository orderMasterRepository;

    //创建订单时候发送消息
    @Autowired
    private WebSocket webSocket;

    @Autowired
    private PushMessageServiceImpl pushMessageService;

    BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);



    String orderId = KeyUtil.genUniqueKey();
    String detailId = KeyUtil.genUniqueKey();
    /**查询商品（库存， 价格）
     * 计算总价
     * 写入订单数据库
     * 扣库存
     */


    @Override
    @Transactional
    //创建订单
    public OrderDTO create(OrderDTO orderDTO) {

//        前端 -- controller -- service -- 这个实现层回传一个 orderDTO 对象， 然后再这里实现逻辑存储。
        String orderId = KeyUtil.genUniqueKey();
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);

//        List<CartDTO> cartDTOList = new ArrayList<>();

        //1. 查询商品（数量, 价格）
        for (OrderDetail orderDetail: orderDTO.getOrderDetailList()) {
            ProductInfo productInfo =  productInfoService.findOne(orderDetail.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            //2. 计算订单总价
            orderAmount = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);

            //订单详情入库
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetailRepository.save(orderDetail);

//            CartDTO cartDTO = new CartDTO(orderDetail.getProductId(), orderDetail.getProductQuantity());
//            cartDTOList.add(cartDTO);
        }


        //3. 写入订单数据库（orderMaster和orderDetail）
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        //这个方法的顺序很重要，覆盖的。
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);

        //4. 扣库存
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e ->
                new CartDTO(e.getProductId(), e.getProductQuantity())
        ).collect(Collectors.toList());
        productInfoService.decreaseStock(cartDTOList);

        // 发送websocket消息
        webSocket.sendMessage(orderDTO.getOrderId());

        return orderDTO;
    }


    /** 查询顾客的单个订单. */
    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster orderMaster = orderMasterRepository.findOne(orderId);
        if(orderMaster == null){
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        // 一个人可以买多个商品 == 一个orderMaster : 多个 orderDetail
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if(CollectionUtils.isEmpty(orderDetailList)){
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        webSocket.sendMessage("查找订单测试成功");
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable);
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());
        Page<OrderDTO> orderDTOPage = new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterPage.getTotalElements());
        // 发送websocket消息
        webSocket.sendMessage("您有一条新消息，[查找列表]");
        return orderDTOPage;
    }

    @Override
    public OrderDTO cancel(OrderDTO orderDTO) {

        //1.  查询判断数据库订单的状态，已取消，就放弃
        OrderMaster orderMaster = new OrderMaster();

        if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("【取消订单】订单状态错误");
            throw new SellException(ResultEnum.ORDER_STATUS_EROR);
        }

        //更改数据库订单的状态
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());

        //保存之后会返回一个对象
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);

        if(updateResult == null){
            log.error("【取消订单】 更新失败， orderMaster={}", updateResult);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        //重新存储修改的产品信息，退回库存
        //还要判断一下在数据库中有没有这个商品
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("【取消订单】订单中无商品详情，orderDTO={}",orderDTO);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }


        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList()
                .stream()
                .map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        //增加库存
        productInfoService.increaseStock(cartDTOList);


        //如果支付成功 --- 最后还得退款
        if(orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())){
            //TODO
        }

        webSocket.sendMessage("取消成功,  hahaha !");
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
//        判断订单状态
        if( !(OrderStatusEnum.FINISHED.getCode().equals(orderDTO.getOrderStatus())) ){
            log.info("【[支付完成]订单状态错误】 orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_EROR);
        }
//        判断支付状态
        if( !(PayStatusEnum.WAIT.getCode().equals(orderDTO.getPayStatus())) ){
            log.info("【[支付完成]订单支付状态错误】payStatus={}, orderId={}",PayStatusEnum.WAIT.getCode(), orderDTO.getPayStatus());
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }
//        改变支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster result = orderMasterRepository.save(orderMaster);
        if (result == null){
            log.info("[支付完成]更新支付状态失败：paystatus={}", ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

//    商家查询所有人的订单
    @Override
    public Page<OrderDTO> findList(Pageable pageable) {
        // 1. 调用 jpa代理层的查询全部方法
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findAll(pageable);
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());
        // 2. 转换 并返回 查询的数据
//        Page<OrderDTO> orderDTOPage = new PageImpl<>(orderDTOList,pageable,orderMasterPage.getTotalElements());

//        public PageImpl(List<T> content, Pageable pageable, long total)
        return new PageImpl<>(orderDTOList,pageable,orderMasterPage.getTotalElements());
    }

    /**订单完结**/
    @Override
    public OrderDTO finish(OrderDTO orderDTO) {

        //1.  判断订单的状态
        if(! (orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode()))){
            log.info("【完结订单：订单状态不正确】: orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_EROR);
        }

    //2.改变订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster result = orderMasterRepository.save(orderMaster);
        if (result == null){
            log.info("【更新失败】：订单更新失败 orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.UPDATE_ORDER_ERROR);
        }

        webSocket.sendMessage("完结订单成功");

        return orderDTO;
    }
}
